function thisrender(this, opts)
%THISRENDER Render the FDATool

%   Author(s): J. Schickler
%   Copyright 1988-2009 The MathWorks, Inc.
%   $Revision: 1.28.4.22 $  $Date: 2009/11/13 05:03:52 $

% Determine the figure position relative to screen size and resolution
sz = fdatool_gui_sizes(this);
menucbs = menus_cbs(this);  % get structure of all local callback functions

% Keep figure invisible until all the uicontrols are displayed.
hFig = figure('IntegerHandle', 'off', ...
    'Color', 'default', ...
    'VIsible', 'Off', ...
    'DoubleBuffer','On', ...
    'MenuBar', 'none', ...
    'WindowStyle', 'normal', ... %WindowStyle before Resize to avoid docking issues.
    'Resize', 'Off', ...
    'Name', opts.title, ... 
    'DockControls', 'Off', ...
    'NextPlot', 'add', ...
    'CloseRequestFcn', menucbs.exit_cb, ...
    'NumberTitle', 'off', ...
    'Units', 'pixels', ...
    'Pointer', 'Watch', ...
    'HandleVisibility', 'Callback', ...
    'Tag', 'Initializing', ...
    'UserData', opts, ...
    'Position', sz.figpos, ...
    'Color', get(0,'defaultUicontrolBackgroundColor'));

sigsetappdata(hFig, 'fdatool', 'handle', this);
set(this, 'FigureHandle', hFig);

% Render the status box.
status = 'Initializing Filter Design and Analysis Tool';
render_statusbar(hFig, status, 'Visible', 'On');

set(hFig, 'Visible', 'On');

% Render the menus.
% Set up main menus
menus = {...
        '&File',...
        '&Edit',...
        '&Analysis',...
        'Ta&rgets',...
        'View', ...
        '&Window'};
callbacks = {[],[],[],[],[],'winmenu(gcbo);'};
tags = {'file',...
        'edit',...
        'analysis', ...
        'targets',...
        'view', ...
        'winmenu'};
for i=1:length(menus),
    h.menus.main(i) = uimenu(hFig,'label',menus{i},...
        'tag',tags{i}, ...
        'Visible', 'Off', ...
        'Callback',callbacks{i});
end

% setup File menu items. 
str2match = '&File';
menus = {...
        '&New Session',...
        '&Open Session...',...
        '&Save Session',...
        'Save Session &As...',...
        'Store Filter...', ...
        '&Export...',...
        'Generate M-file', ...
        'Print Pre&view',...
        '&Print...',...
        'Close'};
tags = {...
        'new',...
        'open',...
        'save',...
        'saveas',...
        'storefilter',...
        'export',...
        'genmcode', ...
        'printprev',...
        'print',...
        'exit'};
callbacks = {...
        menucbs.new_cb,...
        menucbs.open_cb,...
        menucbs.save_cb,...
        menucbs.saveas_cb,...
        {menucbs.method, this, 'filtermanager', [], 'save'}, ...
        menucbs.export_cb,...
        {menucbs.method, this, 'genmcode'}, ...
        menucbs.printprev_cb,...
        menucbs.print_cb,...
        menucbs.exit_cb};
accelerators = {...
        'n',...
        'o',...
        's',...
        '',...
        '',...
        'e',...
        '', ...
        '',...
        'p',...
        ''};  
% indicate which items have separators and which don't
separator_indx = [5 6 8 10];

if ~opts.flags.filtermanager
    tags(5) = [];
    accelerators(5) = [];
    callbacks(5)    = [];
    menus(5)        = [];
    separator_indx  = [separator_indx(1) separator_indx(3:4)-1];
end

if ~opts.flags.newsession
    tags(1)         = [];
    accelerators(1) = [];
    callbacks(1)    = [];
    menus(1)        = [];
    separator_indx = separator_indx-1;
end

for i = 1:length(menus),
    if any(i == separator_indx),
        separator = 'on';
    else
        separator = 'off';
    end
    
    h.menus.file(i) = uimenu(h.menus.main(1), ...
        'label',menus{i},...
        'separator',separator,...
        'Callback',callbacks{i},...
        'Accelerator',accelerators{i},...
        'tag',tags{i});
end

set(h.menus.file(2), 'Interruptible', 'Off');

render_zoommenus(hFig, [5 1], 'defaultview');
winmenu(hFig);  % Initialize the submenu

h.menus.targets = uimenu('Parent', h.menus.main(4), 'Label', 'Generate C header ...', ...
    'Callback', {menucbs.method, this, 'cheader'}, 'Tag', 'cheader');

pos = 7; % Position on menubar

% % Render basic Signal Processing Toolbox Help menu. 
[hhelpmenu h.menus.help] = render_spthelpmenu(hFig, pos);
set(hhelpmenu, 'Visible', 'Off');

% Store the handle to the "Help" menu back in h.main
h.menus.main = [h.menus.main(1:pos-1),hhelpmenu,h.menus.main(pos:end)];

% Render "FDATool Help" separately so that it is on top of "Signal  
% Processing Toolbox Help" (which is rendered by render_spthelpmenu.m 
help_handles = fdatool_help;
h.menus.help = [h.menus.help addmenu(hFig,[pos 1],'FDATool &Help',... 
        help_handles.toolhelp_cb,'toolhelp','Off')];
 
% Common FDATool Help menu items 
menuitems = {'&What''s This?',... 
        'Tip of the Day', ...
        '&Importing Filters', ...
        '&Exporting Filters', ...
        '&Saving/Opening Sessions'}; 
cbs = {help_handles.HelpWhatsThis_cb,... 
        {@tipoftheday_cb,this} ...
        help_handles.importhelp_cb,... 
        help_handles.exporthelp_cb,... 
        help_handles.saveopensessionshelp_cb}; 
tags = {'whatsthis',... 
        'tipoftheday', ...
        'importhelp', ...
        'exporthelp', ...
 'saveopensessionhelp'}; 
sep = {'On','On', 'On','Off','Off'}; 

% Add the menu items to FDATool's Help menu 
h.menus.help = [h.menus.help addmenu(hFig,[pos 3],menuitems,cbs,tags,sep)];

% Render the toolbar.
% Render a Toolbar
h.toolbar.main = uitoolbar('Parent',hFig,'visible', 'off');

% Render standard buttons (New, Open, Print, Print Preview)

% Load new, open, save print and print preview icons.
bmp = load('mwtoolbaricons');

% -------- FILE PUSHBUTTONS --------
% Cell array of cdata (properties) for the toolbar icons 
% that are file pushbuttons (New, Open, Save, and Print)
pushbuttons = {...
        bmp.newdoc,...
        bmp.opendoc,...
        bmp.savedoc,...
        bmp.printdoc,...
        bmp.printprevdoc};

% List the corresponding tooltips
tooltips = {...
        'New session',...
        'Open session',...
        'Save session',...
        'Print current response',...
        'Print preview'};

% List tags for the pushbuttons
tags = {...
        'newsession',...
        'opensession',...
        'savesession',...
        'printresp',...
        'printprev'};

% List callbacks for pushbuttons
cbs = {...
        menucbs.new_cb,...
        menucbs.open_cb,...
        menucbs.save_cb,...
        menucbs.print_cb,...
        menucbs.printprev_cb};

if ~opts.flags.newsession
    pushbuttons(1) = [];
    tooltips(1)    = [];
    tags(1)        = [];
    cbs(1)         = [];
end

% Render the pushbuttons
for indx = 1:length(tags)
    h.toolbar.(tags{indx}) = uipushtool(h.toolbar.main, ...
        'CData', pushbuttons{indx}, ...
        'ClickedCallback', cbs{indx}, ...
        'Tag', tags{indx}, ...
        'Tooltip', tooltips{indx});
end

set(h.toolbar.opensession, 'Interruptible', 'Off');

% set([h.toolbar.undo h.toolbar.redo], 'Enable', 'Off');

% % Install the UNDO manager so its icons will be first
% sigsetappdata(this.FigureHandle, 'siggui', 'HasUndo', true);

% uimenu(h.menus.main(2), ...
%     'Label', 'Undo', ...
%     'Enable', 'Off', ...
%     'Tag', 'undo', ...
%     'Accelerator', 'z', ...
%     'Position', 1);
% uimenu(h.menus.main(2), ...
%     'Label', 'Redo', ...
%     'Enable', 'Off', ...
%     'Tag', 'redo', ...
%     'Accelerator', 'y', ...
%     'Position', 2);

% Render the Zoom In and Zoom Out buttons
render_zoombtns(hFig);

% Render the "Full View Analysis" and "Static Response" buttons
% Load the MAT-file with the icon
load(fullfile(matlabroot, 'toolbox', 'signal', 'sigtools', 'private', 'filtdes_icons.mat'));

% Render the "Full View Analysis" push button.
h.toolbar.fullviewanalysis = uipushtool(h.toolbar.main, ...
    'CData',           bmp.fullviewanalysis, ...
    'ClickedCallback', menucbs.fullviewanalysis_cb,...
    'Tag',             'fullviewanalysis', ...
    'Separator',       'On', ...
    'Tooltip',         'Full view analysis');
h.toolbar.staticresponse = uitoggletool(h.toolbar.main, ...
    'Tag',             'staticresponse', ...
    'Tooltip',         'Filter specifications', ...
    'State',           'On', ...
    'ClickedCallback', {@staticresp_cb, this}, ...
    'Separator',       'on', ...
    'CData',           bmp.illus);

hm = findall(h.menus.main, 'Tag', 'analysis');

h.menu.analysis = uimenu(hm, 'Label', xlate('&Filter Specifications'), ...
    'Callback', {@staticresp_cb, this}, 'Tag', 'filterresponsespecs');

% Render the Analysis frame.
bgc = get(hFig,'Color');

% Position of the frame (axis).
x = sz.fx2;
y = sz.fy1+1;  % Add a pixel; y pos of an axis is different then a frame.
w = sz.fw2;
ht = sz.fh1-1;  % Remove the pixel added a couple of lines above.

% Create an axis to be used as the frame.
h.analysis.frame(1) = axes(...
    'Parent', hFig, ...
    'Units','pixels',...
    'Position',[x y w ht],...
    'Box','On',...
    'Color',bgc,...
    'Tag','analysisframeaxis',...
    'Visible','off',...
    'Xtick',[],...
    'Ytick',[],...
    'Xticklabel',[],...
    'Yticklabel',[]);

h.staticresp = axes('Parent',hFig, ...
    'Units', 'Pixels', ...
    'Position', [277 322 414 169]*sz.pixf, ...
    'Tag', 'staticresponse_axes', ...
    'Visible','Off');

zoomBehavior = hggetbehavior(h.staticresp, 'Zoom');
zoomBehavior.Enable = false;

% Set axis units to normalize so that we can get free cheap resizing.
% NOTE: The function that sets all the units to normalized doesn't catch this axis
% because this axis' handlevisibility is set to off to avoid zooming.
set(h.analysis.frame(1),'Units','Normalized');

% The appdata will be useful to ignore this axes from being zoomed
setappdata(h.analysis.frame(1),'zoomable','off')

% Determine the width extent of the label for the frame.
frLabel = {'Filter Specifications'};
frLabelW = largestuiwidth(frLabel); % 95;

% Render the label.
frameLabelPos = [x+sz.lfs (y+ht)-sz.lh/2 frLabelW sz.lh];
h.analysis.frame(2) = uicontrol(...
    'Parent', hFig, ...
    'Style','Text',...
    'Visible', 'Off', ...
    'BackgroundColor',bgc,...
    'HorizontalAlignment','center', ... 
    'Position',frameLabelPos,...
    'Tag','analysisframelabel',...
    'String',frLabel);

% Don't allow zooming in frame (axis).
set(h.analysis.frame(1),'HandleVisibility','off');  

% Analysis frame, the plots and the coefficient viewer.
fdaddcontextmenu(hFig, h.analysis.frame, 'fdatool_display_frame');

% Use axis to create the frame.
h.recessedFr = axes(...
    'Parent', hFig, ...
    'Units','pixels',....
    'Visible','off',...
    'Tag','recessedframe',...
    'Position',sz.panel);
set(h.recessedFr,...
    'Parent', hFig, ...
    'NextPlot', 'ReplaceChildren', ...
    'units','normalized',...
    'xlim',[0 1],'ylim',[0 1]);

zoomBehavior = hggetbehavior(h.recessedFr, 'zoom');
zoomBehavior.Enable = false;

% Create the recessed visual effect with lines.
h.recessedFr(2) = line([0 1 1],[0 0 1],'color','white','linewidth',2,'visible','off', 'Parent', h.recessedFr(1));
h.recessedFr(3) = line([0 0 1],[0 1 1],'color',[1 1 1]*0,'linewidth',1,'visible','off', 'Parent', h.recessedFr(1));

set(h.recessedFr(1),'HandleVisibility','off');  % Don't allow zooming.

set(this, 'Handles', h);

l = [ ...
        handle.listener(this, [this.findprop('FigureTitle') ...
            this.findprop('SubTitle') this.findprop('FileName') ...
            this.findprop('FileDirty')], 'PropertyPostSet', @lcltitle_listener); ...
        handle.listener(this, 'FilterUpdated', @lclmcode_listener);];

set(l, 'CallbackTarget', this);
set(this, 'WhenRenderedListeners', l);

% ---------------------------------------------------------------------
function tipoftheday_cb(hcbo, eventStruct, this)

hFig = getappdata(this, 'tipoftheday');
if ishghandle(hFig)
    figure(hFig);
else
    hFig = tipoftheday('fdatool', @getfdatooltip);
    this.centerfigonfig(hFig);
    setappdata(this, 'tipoftheday', hFig);
end

% ---------------------------------------------------------------------
function staticresp_cb(hcbo, eventStruct, this)

hs = find(this, '-class', 'siggui.sidebar');
h  = find(allchild(hs), '-depth', 0, 'Visible', 'On');

set(h, 'StaticResponse', 'On');
if strcmpi(get(hcbo, 'type'), 'uitoggletool'), set(hcbo, 'state', 'on'); end

hFVT = getcomponent(this, '-class', 'siggui.fvtool');
set(hFVT, 'Analysis', '');
sendstatus(this, 'Ready');


%-------------------------------------------------------------------
function hndls = LOCALpush(hut,cdata,ccbs,tags,sep,ttstr)
% Local function to call UIPUSHTOOL in a loop

% Render the Push buttons
hndls = zeros(1, length(cdata));
for i = 1:length(cdata),
    hndls(i) = uipushtool('Cdata',cdata{i},...
        'Parent',          hut,...
        'ClickedCallback', ccbs{i},...
        'Tag',             tags{i},...
        'Separator',       sep{i},...
        'Visible',         'off', ...
        'Tooltipstring',   ttstr{i});
end

%----------------------------------------------------------------------
function lclmcode_listener(this, eventStruct)

if isempty(this.MCode),
    enab = 'off';
else
    enab = this.Enable;
end

h = get(this, 'Handles');

set(findobj(h.menus.file, 'tag', 'genmcode'), 'Enable', enab);

%----------------------------------------------------------------------
function lcltitle_listener(this, eventStruct)

title = gettitle(this);

% Find the handle to the 'save' item in the file menu to set 
% the enable property.
h_file = gethandles(this,'menus','file');
h_save = findobj(h_file,'tag','save');

if get(this, 'FileDirty'),
    set(h_save,'enable','on');
else
    set(h_save,'enable','off');
end

set(this.FigureHandle, 'name', title);

% [EOF]
